"""
球队相关 API
"""
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from typing import List
from loguru import logger
from app.core.database import get_db
from app.core.dependencies import get_current_user
from app.schemas.team import (
    TeamResponse, TeamCreate, TeamUpdate,
    TeamMemberResponse, TransferCaptainRequest, RemoveMemberRequest, LeaveTeamRequest
)
from app.schemas.common import ApiResponse
from app.models.team import Team, TeamMember
from app.models.user import User
from app.utils.helpers import generate_id
import json

router = APIRouter()


@router.get("/list", response_model=ApiResponse[List[TeamResponse]])
async def get_team_list(
    keyword: str = Query(None, description="搜索关键词"),
    city_id: str = Query(None, description="城市ID"),
    page: int = Query(1, ge=1),
    page_size: int = Query(10, ge=1, le=50),
    db: Session = Depends(get_db)
):
    """获取球队列表（支持搜索和筛选）"""
    query = db.query(Team)
    
    # 关键词搜索
    if keyword:
        query = query.filter(Team.name.contains(keyword))
    
    # 城市筛选
    if city_id:
        query = query.filter(Team.city_id == city_id)
    
    # 分页
    offset = (page - 1) * page_size
    teams = query.offset(offset).limit(page_size).all()
    
    return ApiResponse(
        data=[TeamResponse(**team.to_dict()) for team in teams]
    )


@router.get("/my-teams", response_model=ApiResponse[List[TeamResponse]])
async def get_my_teams(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取我的球队列表：包含本人担任队长的所有球队，以及通过 team_ids 关联的所有球队，合并不重复。"""
    # 已加入球队 id
    team_ids = set(current_user.team_ids or [])

    # 担任队长的球队
    captain_teams = db.query(Team).filter(Team.captain_id == current_user.id).all()
    for team in captain_teams:
        team_ids.add(team.id)

    if not team_ids:
        return ApiResponse(data=[])
    teams = db.query(Team).filter(Team.id.in_(team_ids)).all()
    return ApiResponse(
        data=[TeamResponse(**team.to_dict()) for team in teams]
    )


@router.get("/detail/{team_id}", response_model=ApiResponse[TeamResponse])
async def get_team_detail(
    team_id: str,
    db: Session = Depends(get_db)
):
    """获取球队详情"""
    team = db.query(Team).filter(Team.id == team_id).first()
    if not team:
        raise HTTPException(status_code=404, detail="球队不存在")
    
    return ApiResponse(data=TeamResponse(**team.to_dict()))


@router.post("/create", response_model=ApiResponse[TeamResponse])
async def create_team(
    team_data: TeamCreate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """创建球队"""
    # 创建球队
    team = Team(
        id=generate_id(),
        name=team_data.name,
        logo=team_data.logo,
        description=team_data.description,
        captain_id=current_user.id,
        captain_name=current_user.nick_name,
        max_members=team_data.maxMembers,
        member_count=1,
        city_id=team_data.cityId
    )
    db.add(team)
    
    # 添加队长为成员
    member = TeamMember(
        id=generate_id(),
        team_id=team.id,
        user_id=current_user.id,
        user_name=current_user.nick_name,
        avatar=current_user.avatar,
        positions=json.dumps(current_user.positions or []),
        role="captain"
    )
    db.add(member)
    
    # 更新用户的球队列表
    if not current_user.team_ids:
        current_user.team_ids = []
    current_user.team_ids.append(team.id)
    
    db.commit()
    db.refresh(team)
    
    return ApiResponse(data=TeamResponse(**team.to_dict()))


@router.put("/update/{team_id}", response_model=ApiResponse[TeamResponse])
async def update_team(
    team_id: str,
    team_data: TeamUpdate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """更新球队信息"""
    team = db.query(Team).filter(Team.id == team_id).first()
    if not team:
        raise HTTPException(status_code=404, detail="球队不存在")
    
    # 检查权限（只有队长可以更新）
    if team.captain_id != current_user.id:
        raise HTTPException(status_code=403, detail="只有队长可以修改球队信息")
    
    # 更新数据
    update_data = team_data.model_dump(exclude_unset=True)
    for field, value in update_data.items():
        db_field = field

        # 字段映射
        if field == "maxMembers":
            db_field = "max_members"
        elif field == "cityId":
            db_field = "city_id"
        elif field == "cityName":
            db_field = "city_name"
        elif field == "foundedDate":
            db_field = "founded_date"
        
        if hasattr(team, db_field):
            setattr(team, db_field, value)
    
    db.commit()
    db.refresh(team)
    
    return ApiResponse(data=TeamResponse(**team.to_dict()))


@router.post("/join", response_model=ApiResponse[str])
async def join_team(
    teamId: str,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """加入球队"""
    team = db.query(Team).filter(Team.id == teamId).first()
    if not team:
        raise HTTPException(status_code=404, detail="球队不存在")
    
    # 检查是否已加入
    existing_member = db.query(TeamMember).filter(
        TeamMember.team_id == teamId,
        TeamMember.user_id == current_user.id
    ).first()
    if existing_member:
        raise HTTPException(status_code=400, detail="已加入该球队")
    
    # 检查人数限制
    if team.member_count >= team.max_members:
        raise HTTPException(status_code=400, detail="球队人数已满")
    
    # 添加成员
    member = TeamMember(
        id=generate_id(),
        team_id=teamId,
        user_id=current_user.id,
        user_name=current_user.nick_name,
        avatar=current_user.avatar,
        positions=json.dumps(current_user.positions or []),
        role="member"
    )
    db.add(member)
    
    # 更新球队人数
    team.member_count += 1
    
    # 更新用户的球队列表
    if not current_user.team_ids:
        current_user.team_ids = []
    current_user.team_ids.append(teamId)
    
    db.commit()
    
    return ApiResponse(data="加入成功")


@router.get("/members/{team_id}", response_model=ApiResponse[List[TeamMemberResponse]])
async def get_team_members(
    team_id: str,
    db: Session = Depends(get_db)
):
    """获取球队成员列表"""
    members = db.query(TeamMember).filter(TeamMember.team_id == team_id).all()
    return ApiResponse(
        data=[TeamMemberResponse(**member.to_dict()) for member in members]
    )


@router.post("/leave", response_model=ApiResponse[str])
async def leave_team(
    request: LeaveTeamRequest,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """离开球队"""
    team = db.query(Team).filter(Team.id == request.teamId).first()
    if not team:
        raise HTTPException(status_code=404, detail="球队不存在")
    
    # 队长不能直接离开，需要先转让或解散
    if team.captain_id == current_user.id:
        raise HTTPException(status_code=400, detail="队长需要先转让队长职位或解散球队")
    
    # 删除成员记录
    member = db.query(TeamMember).filter(
        TeamMember.team_id == request.teamId,
        TeamMember.user_id == current_user.id
    ).first()
    if member:
        db.delete(member)
        team.member_count -= 1
    
    # 更新用户的球队列表
    if current_user.team_ids and request.teamId in current_user.team_ids:
        current_user.team_ids.remove(request.teamId)
    
    db.commit()
    
    return ApiResponse(data="已离开球队")


@router.post("/dismiss/{team_id}", response_model=ApiResponse[str])
async def dismiss_team(
    team_id: str,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """解散球队"""
    team = db.query(Team).filter(Team.id == team_id).first()
    if not team:
        raise HTTPException(status_code=404, detail="球队不存在")
    
    # 检查权限（只有队长可以解散）
    if team.captain_id != current_user.id:
        raise HTTPException(status_code=403, detail="只有队长可以解散球队")
    
    # 删除所有成员
    db.query(TeamMember).filter(TeamMember.team_id == team_id).delete()
    
    # 更新所有成员的team_ids
    members = db.query(TeamMember).filter(TeamMember.team_id == team_id).all()
    for member in members:
        user = db.query(User).filter(User.id == member.user_id).first()
        if user and user.team_ids and team_id in user.team_ids:
            user.team_ids.remove(team_id)
    
    # 删除球队
    db.delete(team)
    db.commit()
    
    return ApiResponse(data="球队已解散")


@router.post("/kick-member", response_model=ApiResponse[str])
async def kick_member(
    team_id: str,
    user_id: str,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """踢出成员"""
    team = db.query(Team).filter(Team.id == team_id).first()
    if not team:
        raise HTTPException(status_code=404, detail="球队不存在")
    
    # 检查权限（只有队长可以踢人）
    if team.captain_id != current_user.id:
        raise HTTPException(status_code=403, detail="只有队长可以踢出成员")
    
    # 不能踢自己
    if user_id == current_user.id:
        raise HTTPException(status_code=400, detail="不能踢出自己")
    
    # 删除成员记录
    member = db.query(TeamMember).filter(
        TeamMember.team_id == team_id,
        TeamMember.user_id == user_id
    ).first()
    
    if not member:
        raise HTTPException(status_code=404, detail="成员不存在")
    
    db.delete(member)
    team.member_count -= 1
    
    # 更新用户的球队列表
    user = db.query(User).filter(User.id == user_id).first()
    if user and user.team_ids and team_id in user.team_ids:
        user.team_ids.remove(team_id)
    
    db.commit()
    
    return ApiResponse(data="已踢出成员")


@router.post("/transfer-captain", response_model=ApiResponse[str])
async def transfer_captain(
    request: TransferCaptainRequest,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """转让队长"""
    team = db.query(Team).filter(Team.id == request.teamId).first()
    if not team:
        raise HTTPException(status_code=404, detail="球队不存在")
    
    # 检查权限（只有队长可以转让）
    if team.captain_id != current_user.id:
        raise HTTPException(status_code=403, detail="只有队长可以转让队长职位")
    
    # 检查新队长是否是成员
    new_captain_member = db.query(TeamMember).filter(
        TeamMember.team_id == request.teamId,
        TeamMember.user_id == request.newCaptainId
    ).first()
    
    if not new_captain_member:
        raise HTTPException(status_code=404, detail="新队长不是球队成员")
    
    # 获取新队长信息
    new_captain = db.query(User).filter(User.id == request.newCaptainId).first()
    if not new_captain:
        raise HTTPException(status_code=404, detail="用户不存在")
    
    # 更新旧队长角色
    old_captain_member = db.query(TeamMember).filter(
        TeamMember.team_id == request.teamId,
        TeamMember.user_id == current_user.id
    ).first()
    if old_captain_member:
        old_captain_member.role = "member"
    
    # 更新新队长角色
    new_captain_member.role = "captain"
    
    # 更新球队队长信息
    team.captain_id = request.newCaptainId
    team.captain_name = new_captain.nick_name
    
    db.commit()
    
    return ApiResponse(data="队长转让成功")


@router.get("/invite-code/{team_id}", response_model=ApiResponse[dict])
async def get_invite_code(
    team_id: str,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取球队邀请码（含过期时间）"""
    from datetime import datetime, timedelta
    import hashlib
    
    team = db.query(Team).filter(Team.id == team_id).first()
    if not team:
        raise HTTPException(status_code=404, detail="球队不存在")
    
    # 检查是否为队长
    if team.captain_id != current_user.id:
        raise HTTPException(status_code=403, detail="只有队长可以查看邀请码")
    
    # 生成每日邀请码（基于team_id和当天日期）
    today = datetime.now().strftime("%Y-%m-%d")
    code_source = f"{team_id}_{today}"
    invite_code = hashlib.md5(code_source.encode()).hexdigest()[:8].upper()
    
    # 计算过期时间（当天23:59:59）
    expires_at = datetime.now().replace(hour=23, minute=59, second=59, microsecond=0)
    
    return ApiResponse(data={
        "code": invite_code,
        "qrContent": f"TEAM_INVITE:{invite_code}",
        "expiresAt": expires_at.isoformat()
    })


@router.get("/qrcode/{team_id}", response_model=ApiResponse[dict])
async def get_team_qrcode(
    team_id: str,
    db: Session = Depends(get_db)
):
    """获取球队二维码（每天更新一次）"""
    from datetime import datetime, timedelta
    import hashlib
    
    team = db.query(Team).filter(Team.id == team_id).first()
    if not team:
        raise HTTPException(status_code=404, detail="球队不存在")
    
    # 生成今日的日期标识
    today = datetime.now().strftime('%Y-%m-%d')
    
    # 生成二维码内容：team_id + 日期 + 盐值
    # 这样每天的二维码都不同，但同一天内保持不变
    salt = "football_team_qrcode_salt"
    qr_content = f"{team_id}|{today}|{salt}"
    
    # 生成哈希值作为短码
    qr_hash = hashlib.md5(qr_content.encode()).hexdigest()[:12]
    
    # 二维码数据：包含team_id和日期哈希
    qr_data = f"TEAM:{team_id}:{qr_hash}"
    
    # 计算二维码过期时间（明天0点）
    tomorrow = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0) + timedelta(days=1)
    expires_at = tomorrow.isoformat()
    
    return ApiResponse(data={
        "qrContent": qr_data,
        "teamId": team_id,
        "teamName": team.name,
        "teamLogo": team.logo,
        "expiresAt": expires_at,
        "qrHash": qr_hash,
        "generatedDate": today
    })


@router.post("/join-by-qrcode", response_model=ApiResponse[str])
async def join_by_qrcode(
    qr_content: str,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """通过二维码加入球队"""
    from datetime import datetime
    import hashlib
    
    try:
        # 解析二维码内容：TEAM:team_id:qr_hash
        parts = qr_content.split(':')
        if len(parts) != 3 or parts[0] != 'TEAM':
            raise HTTPException(status_code=400, detail="无效的二维码")
        
        team_id = parts[1]
        qr_hash = parts[2]
        
        # 验证二维码是否有效（检查是否是今天生成的）
        today = datetime.now().strftime('%Y-%m-%d')
        salt = "football_team_qrcode_salt"
        expected_content = f"{team_id}|{today}|{salt}"
        expected_hash = hashlib.md5(expected_content.encode()).hexdigest()[:12]
        
        if qr_hash != expected_hash:
            raise HTTPException(status_code=400, detail="二维码已过期，请获取最新二维码")
        
        # 调用加入球队逻辑
        return await join_team(team_id, current_user, db)
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=400, detail=f"二维码格式错误: {str(e)}")


@router.post("/join-by-code", response_model=ApiResponse[str])
async def join_by_invite_code(
    invite_code: str,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """通过邀请码加入球队"""
    from datetime import datetime
    import hashlib
    
    # 验证邀请码
    today = datetime.now().strftime("%Y-%m-%d")
    
    # 查找所有球队，验证邀请码
    teams = db.query(Team).all()
    target_team = None
    
    for team in teams:
        code_source = f"{team.id}_{today}"
        expected_code = hashlib.md5(code_source.encode()).hexdigest()[:8].upper()
        if expected_code == invite_code.upper():
            target_team = team
            break
    
    if not target_team:
        raise HTTPException(status_code=400, detail="无效或过期的邀请码")
    
    # 检查是否已是成员
    if current_user.id in (target_team.member_ids or []):
        raise HTTPException(status_code=400, detail="你已经是该球队成员")
    
    # 检查球队是否已满
    if target_team.member_count >= target_team.max_members:
        raise HTTPException(status_code=400, detail="球队人数已满")
    
    # 添加成员
    member_ids = target_team.member_ids or []
    member_ids.append(current_user.id)
    target_team.member_ids = member_ids
    target_team.member_count += 1
    
    # 更新用户球队列表
    user_team_ids = current_user.team_ids or []
    user_team_ids.append(target_team.id)
    current_user.team_ids = user_team_ids
    
    db.commit()
    
    return ApiResponse(data="加入球队成功")


@router.get("/search", response_model=ApiResponse[List[TeamResponse]])
async def search_teams(
    keyword: str = Query(None, description="搜索关键词"),
    filter: str = Query("all", description="筛选条件: all/recruiting/nearby"),
    page: int = Query(1, ge=1),
    pageSize: int = Query(20, ge=1, le=50),
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """搜索球队"""
    query = db.query(Team)
    
    # 关键词搜索
    if keyword:
        query = query.filter(Team.name.contains(keyword))
    
    # 筛选条件
    if filter == "recruiting":
        # 招募中的球队（人数未满）
        query = query.filter(Team.member_count < Team.max_members)
    elif filter == "nearby":
        # 同城球队（基于用户城市）
        user_city_id = getattr(current_user, 'city_id', None)
        user_city_name = getattr(current_user, 'city_name', None)
        
        logger.info(f"🏙️  同城筛选 - 用户城市ID: {user_city_id}, 用户城市名: {user_city_name}")
        
        # 优先使用city_name，如果没有则使用city_id
        user_city = user_city_name or user_city_id
        
        if user_city:
            # 同时匹配city_id和city_name字段
            query = query.filter(
                (Team.city_id == user_city) | (Team.city_name == user_city)
            )
            logger.info(f"✅ 筛选同城球队: {user_city}")
        else:
            # 用户未设置城市，显示所有球队（不筛选）
            logger.info(f"ℹ️  用户未设置城市，显示所有球队")
            pass  # 不添加任何筛选条件
    
    # 排除用户已加入的球队
    user_team_ids = current_user.team_ids or []
    if user_team_ids:
        query = query.filter(~Team.id.in_(user_team_ids))
    
    # 分页
    offset = (page - 1) * pageSize
    teams = query.offset(offset).limit(pageSize).all()
    
    # 添加招募状态
    result = []
    for team in teams:
        team_dict = team.to_dict()
        team_dict['isRecruiting'] = team.member_count < team.max_members
        result.append(TeamResponse(**team_dict))
    
    return ApiResponse(data=result)


@router.get("/matches/{team_id}", response_model=ApiResponse[List[dict]])
async def get_team_matches(
    team_id: str,
    db: Session = Depends(get_db)
):
    from app.models.match import Match
    team = db.query(Team).filter(Team.id == team_id).first()
    if not team:
        raise HTTPException(status_code=404, detail="球队不存在")
    try:
        # 容错处理：如果历史表没有这两个字段，直接查不到或者schema不对会except，不500
        matches = db.query(Match).filter(
            getattr(Match, 'home_team_id', None) == team_id if hasattr(Match, 'home_team_id') else False
            |
            getattr(Match, 'away_team_id', None) == team_id if hasattr(Match, 'away_team_id') else False
        ).order_by(Match.date.desc(), Match.start_time.desc()).all()
    except Exception as e:
        from loguru import logger
        logger.error(f"查询比赛时Match.home_team_id/away_team_id报错: {e}")
        matches = []
    result = []
    for match in matches:
        try:
            result.append(match.to_dict())
        except Exception as e:
            from loguru import logger
            logger.error(f"Match.to_dict()报错: {e}")
            continue
    return ApiResponse(data=result)


@router.post("/remove-member", response_model=ApiResponse[str])
async def remove_team_member(
    request: RemoveMemberRequest,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """移除球队成员（队长权限）"""
    team = db.query(Team).filter(Team.id == request.teamId).first()
    if not team:
        raise HTTPException(status_code=404, detail="球队不存在")
    
    # 检查是否为队长
    if team.captain_id != current_user.id:
        raise HTTPException(status_code=403, detail="只有队长可以移除成员")
    
    # 不能移除队长自己
    if request.memberId == current_user.id:
        raise HTTPException(status_code=400, detail="不能移除队长")
    
    # 检查成员是否在球队中
    member_ids = team.member_ids or []
    if request.memberId not in member_ids:
        raise HTTPException(status_code=404, detail="该用户不在球队中")
    
    # 移除成员
    member_ids.remove(request.memberId)
    team.member_ids = member_ids
    team.member_count -= 1
    
    # 删除 TeamMember 记录
    team_member = db.query(TeamMember).filter(
        TeamMember.team_id == request.teamId,
        TeamMember.user_id == request.memberId
    ).first()
    if team_member:
        db.delete(team_member)
    
    # 更新用户的球队列表
    member = db.query(User).filter(User.id == request.memberId).first()
    if member:
        user_team_ids = member.team_ids or []
        if request.teamId in user_team_ids:
            user_team_ids.remove(request.teamId)
            member.team_ids = user_team_ids
    
    db.commit()
    
    return ApiResponse(data="移除成功")

